<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-form
        :model="queryInfo"
        ref="queryForm"
        :inline="true"
        v-show="showSearch"
        label-width="68px"
      >
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryInfo.userName"
            placeholder="请输入用户名称"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phonenumber">
          <el-input
            v-model="queryInfo.phonenumber"
            placeholder="请输入手机号码"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryInfo.status"
            placeholder="用户状态"
            clearable
            size="small"
            style="width: 240px"
          >
            <el-option label="启用" :value="1" />
            <el-option label="停用" :value="0" />
          </el-select>
        </el-form-item>
        <!-- <el-row>
          <el-col> -->
        <el-form-item label="创建时间" prop="dateRange">
          <el-date-picker
            v-model="queryInfo.dateRange"
            size="small"
            style="width: 240px"
            value-format="yyyy-MM-dd"
            type="daterange"
            class="mgr10"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getUserList"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
        <!-- <el-form-item> </el-form-item> -->
        <!-- </el-col>
        </el-row> -->
      </el-form>
      <el-row type="flex" justify="space-between">
        <el-col
          ><el-button
            type="primary"
            icon="el-icon-plus"
            v-hasPermi="['sys:user:add']"
            size="small"
            plain
            @click="handleAddUser"
            >新增用户</el-button
          >
        </el-col>
        <el-col class="tr">
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getUserList"
            :columns="columns"
          ></right-toolbar>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table
        :data="userList"
        border
        stripe
        class="mgt10"
        v-loading="loading"
      >
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          v-if="columns[0].visible"
        ></el-table-column>
        <el-table-column
          prop="nickName"
          label="昵称"
          v-if="columns[1].visible"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          v-if="columns[2].visible"
        ></el-table-column>
        <el-table-column
          prop="roleName"
          label="角色"
          v-if="columns[3].visible"
        ></el-table-column>
        <el-table-column label="创建时间" width="160" v-if="columns[4].visible">
          <template #default="{ row }">
            {{ row.createTime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column label="状态" v-if="columns[5].visible">
          <template #default="{ row }">
            <el-link
              class="fw700"
              type="primary"
              :underline="false"
              v-if="row.status"
              >启用</el-link
            >
            <el-link class="fw700" :underline="false" type="info" v-else
              >停用</el-link
            >
            <el-switch
              class="mgl10"
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              v-if="row.isHidden"
              v-hasPermi="['sys:user:setStatus']"
              @change="userStateChange(row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              v-hasPermi="['sys:user:edit']"
              @click="showEditDialog(row)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              v-hasPermi="['sys:user:delete']"
              size="mini"
              v-if="row.isHidden"
              @click="removeUserById(row.userId)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              v-if="row.isHidden"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
              v-hasPermi="['sys:user:setRole']"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        background
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      ></el-pagination>
    </el-card>
    <!-- 添加用户对话框 -->

    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      class="adduser-dialog"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="addRules"
        label-width="80px"
      >
        <el-row type="flex">
          <el-col>
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="addForm.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="昵称：" prop="nickname">
              <el-input v-model="addForm.nickname"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="addForm.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="手机：" prop="mobile">
              <el-input v-model="addForm.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <el-form-item label="角色：" prop="roles">
              <el-select v-model="addForm.roles" placeholder="请选择">
                <el-option
                  v-for="item in rolesList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="状态：" prop="status">
              <el-radio-group v-model="addForm.status" placeholder="请选择状态">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="addDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      class="adduser-dialog"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="editRules"
        label-width="80px"
      >
        <el-row type="flex">
          <el-col>
            <el-form-item label="用户名：" prop="username">
              <el-input v-model="editForm.username"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="昵称：" prop="nickname">
              <el-input v-model="editForm.nickname"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex">
          <el-col>
            <el-form-item label="邮箱：" prop="email">
              <el-input v-model="editForm.email"></el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="手机：" prop="mobile">
              <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row type="flex" v-hasPermi="['sys:user:setStatus']">
          <el-col>
            <el-form-item label="状态：" prop="status">
              <el-radio-group
                :disabled="!editForm.isHidden"
                v-model="editForm.status"
                placeholder="请选择状态"
              >
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col> </el-col>
        </el-row>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="450px"
      class="adduser-dialog"
      @close="setRoleDialogClosed"
    >
      <!-- 内容主题区域 -->
      <div>
        <el-form
          :model="roleForm"
          ref="roleFormRef"
          :rules="roleRules"
          label-width="100px"
        >
          <el-form-item label="当前用户：">
            {{ userInfo.username }}
          </el-form-item>
          <el-form-item label="当前角色：">
            {{ userInfo.roleName }}
          </el-form-item>
          <el-form-item label="新角色：" prop="selectedRoleId">
            <el-select
              v-model="roleForm.selectedRoleId"
              placeholder="请选择新角色"
            >
              <el-option
                v-for="item in rolesList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllUser,
  stateChange,
  addUser,
  getUser,
  editUser,
  delUser,
  updateUserRoles
} from '@/api/user'
import RightToolbar from '@/components/RightToolbar'
import { getRoles } from '@/api/role'
export default {
  components: {
    RightToolbar
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 列信息
      columns: [
        { key: 0, label: `姓名`, visible: true },
        { key: 1, label: `昵称`, visible: true },
        { key: 2, label: `电话`, visible: true },
        { key: 3, label: `角色`, visible: true },
        { key: 4, label: `创建时间`, visible: true },
        { key: 5, label: `状态`, visible: true }
      ],
      // 显示搜索条件
      showSearch: true,
      // 获取用户列表得参数对象
      // 查询参数
      queryInfo: {
        pagenum: 1,
        pagesize: 5,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        // 日期范围
        dateRange: []
      },
      statusOptions: [],
      // queryInfo: {
      //   query: '',
      //   pagenum: 1,
      //   pagesize: 5
      // },
      // 用户列表
      userList: [],
      // 用户总数
      total: 0,
      // 控制添加用户对话框得显示与隐藏
      addDialogVisible: false,
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 添加用户得表单数据
      addForm: {
        // 用户名-真实姓名
        username: '',
        // 用户昵称
        nickname: '',
        // 邮箱
        email: '',
        // 手机
        mobile: '',
        roles: '', // 角色
        status: 1 // 状态
      },
      // 添加用户得表单校验
      addRules: {
        roles: [
          // 用户角色
          { required: true, message: '请选择用户角色', trigger: 'change' }
        ],
        status: [
          // 用户状态
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // 用户名表单校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        // 密码表单校验
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
          // {
          //   min: 6,
          //   max: 15,
          //   message: '密码的长度在6~15个字符之间',
          //   trigger: 'blur'
          // }
        ],
        // 邮箱表单校验
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ],
        // 手机表单校验
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[0123456789]|17[05678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }
        ]
      },
      // 修改用户得表单数据
      editForm: {
        // 用户名-真实姓名
        username: '',
        // 用户昵称
        nickname: '',
        // 邮箱
        email: '',
        // 手机
        mobile: '',
        status: '' // 状态
      },
      // 添加用户得表单校验
      editRules: {
        // 邮箱表单校验
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/,
            message: '邮箱格式不正确',
            trigger: 'blur'
          }
        ],
        // 手机表单校验
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[0123456789]|17[05678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号格式不正确',
            trigger: 'blur'
          }
        ],
        // roles: [
        //   // 用户角色
        //   { required: true, message: '请选择用户角色', trigger: 'change' }
        // ],
        status: [
          // 用户状态
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        // 用户名表单校验
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名的长度在3~10个字符之间',
            trigger: 'blur'
          }
        ]
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色数据列表
      rolesList: [],
      // 选中的新角色的id值
      roleForm: {
        selectedRoleId: ''
      },
      roleRules: {
        selectedRoleId: [{ required: true, message: '请选择要分配的新角色' }]
      }
    }
  },
  created() {
    // 获取用户列表
    this.getUserList()
  },
  methods: {
    /** 重置按钮操作 */
    resetQuery() {
      // 表单重置
      this.$refs.queryForm.resetFields()
      this.getUserList()
    },
    async getAllRoles() {
      const { _RejCode, data } = await getRoles()
      if (_RejCode !== '00000000') return
      this.rolesList = data
    },
    // 点击添加角色
    async handleAddUser() {
      this.addDialogVisible = true
      this.getAllRoles()
    },
    // 获取用户列表
    async getUserList() {
      this.loading = true
      const { _RejCode, data } = await getAllUser(this.queryInfo).catch(
        (err) => err
      )
      this.loading = false
      if (_RejCode !== '00000000') return
      const { users, total } = data
      this.userList = users
      this.total = total
    },
    // 一页显示多少条数据
    handleSizeChange(pageSize) {
      this.queryInfo.pagesize = pageSize
      this.queryInfo.pagenum = 1
      this.getUserList()
    },
    // 当前页数，当前在第几页
    handleCurrentChange(curPage) {
      this.queryInfo.pagenum = curPage
      this.getUserList()
    },
    // 监听状态开关改变
    async userStateChange(row) {
      console.log(row.status)
      const confirmRes = await this.$confirm(
        `确认要"${row.status ? '启用' : '停用'}" "${row.username}"用户吗?`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      if (confirmRes !== 'confirm') {
        this.$set(row, 'status', row.status ? 0 : 1)
        // row.status =
        return this.$message({
          type: 'info',
          message: `已取消${row.status ? '停用' : '启用'}`
        })
      }
      const { _RejCode, _RejMsg } = await stateChange({
        id: row.userId,
        status: row.status
      }).catch((err) => err)
      if (_RejCode !== '00000000') {
        this.$set(row, 'status', row.status ? 0 : 1)
        return
      }
      this.$message.success(_RejMsg)
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // 监听对话框关闭事件，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定按钮，添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        // 可以发起添加用户的网络请求
        const { _RejCode, _RejMsg } = await addUser(this.addForm)
        if (_RejCode !== '00000000') return
        this.$message.success(_RejMsg)
        this.addDialogVisible = false
        // 刷新用户列表
        this.getUserList()
      })
    },
    // 修改按钮 展示编辑用户的对话框
    async showEditDialog(row) {
      const { _RejCode, data } = await getUser({ id: row.userId }).catch(
        (err) => err
      )
      if (_RejCode !== '00000000') return
      this.editForm = data
      this.editDialogVisible = true
      // await this.getAllRoles()
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      // this.$nextTick()
      this.editForm = {
        // 用户名-真实姓名
        username: '',
        // 用户昵称
        nickname: '',
        // 邮箱
        email: '',
        // 手机
        mobile: '',
        status: '' // 状态
      }
      this.$refs.editFormRef.resetFields()
    },
    // 点击确定按钮，修改用户信息
    editUserInfo() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return
        // 发起修改用户的网络请求
        const { _RejCode, _RejMsg } = await editUser({
          id: this.editForm.userId,
          email: this.editForm.email,
          mobile: this.editForm.mobile,
          nickname: this.editForm.nickname,
          username: this.editForm.username,
          status: this.editForm.status
        }).catch((err) => err)
        if (_RejCode !== '00000000') return
        // 关闭弹框
        this.editDialogVisible = false
        // 刷新列表
        this.getUserList()
        // 提示修改成功
        this.$message.success(_RejMsg)
      })
    },
    // 删除用户
    async removeUserById(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      // 如果用户确认删除，则返回值为字符串 confirm
      if (confirmRes !== 'confirm') {
        return this.$message({
          type: 'info',
          message: '已取消删除'
        })
      }
      const { _RejCode, _RejMsg } = await delUser({ id })
      if (_RejCode !== '00000000') return
      // 如果用户取消了删除，则返回值为字符串 cancel
      this.$message.success(_RejMsg)
      // 刷新列表
      this.getUserList()
    },
    // 展示分配角色的对话框
    async setRole(row) {
      this.userInfo = row
      // 在展示对话框之前，获取所有角色的列表
      // const { _RejCode, data } = await getRoles()
      // if (_RejCode !== '00000000') return
      // this.rolesList = data
      await this.getAllRoles()
      this.setRoleDialogVisible = true
    },
    // 点击确定按钮，分配角色
    saveRoleInfo() {
      // if (!this.selectedRoleId) {
      //   return this.$message.error('请选择要分配的角色！')
      // }
      this.$refs.roleFormRef.validate(async (valid) => {
        if (!valid) return
        const { _RejCode, _RejMsg } = await updateUserRoles({
          userId: this.userInfo.userId,
          roleId: this.roleForm.selectedRoleId
        })
        if (_RejCode !== '00000000') return
        this.$message.success(_RejMsg)
        this.getUserList()
        this.setRoleDialogVisible = false
      })
    },
    // 监听分配角色的对话框的关闭事件
    setRoleDialogClosed() {
      // this.roleForm.selectedRoleId = ''
      this.$refs.roleFormRef.resetFields()
      this.userInfo = {}
    }
  }
}
</script>

<style lang="scss" scoped>
.userTable {
  margin-top: 10px;
}
.fw700 {
  font-weight: 700;
}
</style>
